package cn.com.zzl.util;


import java.io.File;
import java.net.URL;
import java.util.Date;

import org.springframework.web.multipart.MultipartFile;

/**
 * Description：上传文件
 * Created by 朱正磊 on 2017-04-26 15:54.
 */
public class UploadFile  {

	/**
	 * @Desc 上传文件并返回存储路径
	 * @param folder WEB-INF下面存储上传文件的目录，比如upload目录
	 * @param suffix 文件后缀
	 * @param file 文件
	 * @return 返回文件全路径
	 * @throws Exception 异常信息
	 */
	public static String upload(String folder, String suffix, MultipartFile file) throws Exception {
		String webinfoPath = getWEBINFPath();
		String materialFilePath = webinfoPath + folder;
		String radomfileName = CalendarUtil.dateToString(new Date(),"yyyyMMddHHmmss") + suffix;
		upload(file,radomfileName,materialFilePath);
		return materialFilePath + "\\" + radomfileName;
	}

	/**
	 * @Desc 获取WEB-INF目录，
	 * 比如D:\workspace\project\ideaProject\demo\example\target\demo\WEB-INF\
	 * @return 返回WEB-INF目录
	 */
	public static String getWEBINFPath(){
		//未处理的path格式为file:/D:/workspace/project/ideaProject/demo/example/target/demo/WEB-INF/classes/
		URL url = Thread.currentThread().getContextClassLoader().getResource("");
		if(url != null){
			String path = url.toString();
			path = path.replace('/', '\\'); // 将/换成\
			path = path.replace("file:", ""); //去掉file:
			path = path.replace("classes\\", ""); //去掉class\
			path = path.substring(1); //去掉第一个\,如 \D:\JavaWeb...
			return path;
		}
		return "";
	}

	/**
	 * @Desc 上传文件
	 * @param file 文件
	 * @param radomfileName 保存文件名
	 * @param materialFilePath 保存路径
	 * @return 返回上传状态，true 上传成功，false 上传失败。
	 */
	public static boolean upload(MultipartFile file, String radomfileName,
								 String materialFilePath) throws Exception {
		boolean flag = true;
		File baseFile = new File(materialFilePath);
		File trainFile = new File(baseFile, radomfileName);
		try {
			if(baseFile.exists() || baseFile.mkdirs()){
				file.transferTo(trainFile);
			}
		} catch (Exception e) {
			flag = false;
		}
		return flag;
	}

}
